<template>
    <div class="app-container">
        <div class="home-bg"></div>
        <div class="home-content">
            <div class="thesis-type">
                <div :class="['item-thesis', activeUid === item.groupUid && 'item-thesis-active']"
                    v-for="(item, index) in thesisType" :key="index" @click="toSelectThesisType(item.groupUid, item.groupName)">
                    <div class="thesis-type-icon">                        
                        <img v-if="activeUid === item.groupUid" src="@/assets/images/lunwen-icon.png" alt="" />
                        <img v-else src="@/assets/images/lunwen-icon2.png" alt="" />                        
                    </div>
                    <div class="thesis-type-name">{{ item.groupName }}</div>
                </div>
            </div>
            <div class="search-area">
                <div class="search-box">
					<span class="el-dropdown-link">
					    关键字
					</span>
					<!--
                    <el-dropdown>                       					
                        <template #dropdown>							
                            <el-dropdown-menu>
                                <el-dropdown-item>主题1</el-dropdown-item>
                                <el-dropdown-item>主题2</el-dropdown-item>
                            </el-dropdown-menu>						
                        </template>
                    </el-dropdown>
					-->
                    <div class="search-input">
                        <el-input v-model.trim="searchText" style="height: 100%; width: 100%;" size="large"
                            placeholder="请输入关键字进行搜索" @keydown.enter="resetQuery"></el-input>
                    </div>

                    <div class="seach-icon" @click="resetQuery">
                        <img src="@/assets/images/search-icon.png" alt=""></img>
                    </div>
                </div>
                <div class="hot-search" v-if="hotSearch.length>0">
                    <span class="hot-saerch-laebl">热门搜索：</span>
                    <div class="hot-search-list">
                        <span class="item-hot-search" v-for="(item, index) in hotSearch" :key="index"
                            @click="toSelectHotSearch(item)">{{ item }}</span>
                    </div>
                </div>
            </div>
            <div class="filter-data-content">
                <div class="filter-box" v-if="cateList.length > 0">
                    <div class="item-filter-type">
                        <div class="item-filter-label">专业类别</div>
                        <div class="item-filter-list">
                            <div :class="['item-filter', oneIdx === index && 'item-filter-active']"
                                v-for="(val, index) in cateList" :key="index" @click="toSelectCate(index)">
                                {{ val.categoryName }}</div>
                        </div>
                    </div>
                    <div class="item-filter-type" v-if="twoList.length > 0">
                        <div class="item-filter-label">细分类别</div>
                        <div class="item-filter-list">
                            <div :class="['item-filter', twoIdx === index && 'item-filter-active']"
                                v-for="(val, index) in twoList" :key="index" @click="toSelectCateTwo(index)">
                                {{ val.categoryName }}</div>
                        </div>
                    </div>
                     <div class="item-filter-type" v-if="threeList.length > 0">
                        <div class="item-filter-label">细分类别</div>
                        <div class="item-filter-list">
                            <div :class="['item-filter', threeIdx === index && 'item-filter-active']"
                                v-for="(val, index) in threeList" :key="index" @click="toSelectCateThree(index)">
                                {{ val.categoryName }}</div>
                        </div>
                    </div>
                </div>

                <div class="search-section">
                    <el-form ref="form" :inline="true" :model="queryParams" size="default" label-width="80">
                        <el-row>
                            <el-col :span="8">
                                <div class="form-flex">
                                    <el-form-item label="字数">
                                        <el-input-number v-model="queryParams.startNumbers" :min="0" clearable
                                            :max="queryParams.endNumbers > 0? queryParams.endNumbers : 1000000" :controls="false" style="width: 100px; margin-right: 10px;" />
                                        —
                                        <el-input-number v-model="queryParams.endNumbers" :min="queryParams.startNumbers > 0? queryParams.startNumbers: 0" clearable
                                            :controls="false" style="width: 100px; margin-left: 10px;" />
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <div class="form-flex">
                                    <el-form-item label="下载次数">
                                        <el-input-number v-model="queryParams.startDownload" :min="0" clearable
                                            :max="queryParams.endDownload > 0? queryParams.endDownload : 1000000" :controls="false" style="width: 100px; margin-right: 10px;" />
                                        —
                                        <el-input-number v-model="queryParams.endDownload" clearable
                                            :min="queryParams.startDownload? queryParams.startDownload : 0" :controls="false" style="width: 100px; margin-left: 10px;" />
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="form-flex" label="查重">
                                    <div class="form-spaceBetween">
                                        <el-checkbox v-model="queryParams.isTraditionDuplicate" label="可过传统查重"
                                        size="large" />
                                        <el-checkbox v-model="queryParams.isAigcDuplicate" label="可过AIGC查重" size="large" />
                                    </div> 
                                </div>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="论文类型" prop="lunwenType">
                                    <el-select v-model="queryParams.lunwenType" placeholder="请选择" style="width: 236px;" clearable>
                                        <el-option :value="item.dictLabel" :label="item.dictLabel"
                                            v-for="item in searchTypeList" :key="item.dictCode">{{ item.dictLabel}}</el-option>
                                    </el-select>
                                </el-form-item>

                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="日期" prop="dateRange">
                                    <el-date-picker v-model="dateRange" type="daterange" clearable range-separator="至" style="width: 236px;"
                                        value-format="YYYY-MM-DD" start-placeholder="开始日期"
                                        end-placeholder="结束日期" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <div class="form-end">
                                    <el-button type="primary" @click="resetQuery">搜索</el-button>
                                </div>
                            </el-col>
                        </el-row>

                    </el-form>
                </div>

                <div class="data-table">
                    <el-table :data="tableData" style="width: 100%; border-radius: 16px 16px 0 0; "
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" align="center" />
                        <el-table-column prop="productNo" label="论文编号" align="center" width="100" />
                        <el-table-column prop="productName" label="题目"  show-overflow-tooltip>
                            <template #default="scope">
                                <span class="product-name" @click="hanldeDetail(scope.row)">{{ scope.row.productName
                                    }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="numbers" label="字数" align="center" width="70" />
                        <el-table-column prop="jifen" label="所需积分" align="center" width="80">
                            <template #default="scope">
                                <div class="item-score">
                                    <div class="item-score-icon"> <img src="@/assets/images/score-icon.png" alt="">
                                    </div>
                                    <div class="item-score-num">{{ scope.row.jifen }}</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="lunwenType" label="论文类型" align="center" width="80"/>
                        <el-table-column prop="createDate" label="上传日期" align="center" width="110" />
                        <el-table-column prop="downloadCount" label="下载次数" align="center" width="80"/>
                        <el-table-column label="是否可过传统查重" align="center" width="90">
                            <template #default="scope">
                                <div class="item-status-icon">
                                    <img v-if="scope.row.isTraditionDuplicate=='1'" src="@/assets/images/pass-icon.png"
                                        alt="">
                                    <img v-else src="@/assets/images/no-pass.png" alt="">
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="是否可过AIGC查重" align="center" width="90">
                            <template #default="scope">
                                <div class="item-status-icon">
                                    <img v-if="scope.row.isAigcDuplicate=='1'" src="@/assets/images/pass-icon.png" alt="">
                                    <img v-else src="@/assets/images/no-pass.png" alt="">
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="90">
                            <template #default="scope">
                                <div class="opt-btn">
                                    <div class="item-opt-img" @click="toCollectPaper(scope.row)">
                                        <el-tooltip :content="scope.row.isCollect == '1' ? '取消收藏' : '收藏'" effect="dark"
                                            placement="top">
                                            <img v-if="scope.row.isCollect == '1'" src="@/assets/images/star-active.png"
                                                alt="">
                                            <img v-else src="@/assets/images/start-icon.png" alt="">
                                        </el-tooltip>
                                    </div>
                                    <div class="item-opt-img" @click="toDownloadPaper(scope.row)">
                                        <el-tooltip content="下载" effect="dark" placement="top">
                                            <img src="@/assets/images/down-icon.png" alt="">
                                        </el-tooltip>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-batch">
                        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :small="false"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />

                        <div>
                            <el-button type="primary" :disabled="multipleSelection.length === 0"
                                @click="toBatchCollect">批量收藏</el-button>
                            <el-button type="primary" :disabled="multipleSelection.length === 0"
                                @click="toBatchDownload">批量下载</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <AdBox top="340px" left="calc((100% - 1100px)/2 - 174px)" />

        <OnlineBox top="340px" left="calc((100% + 1100px)/2 + 24px)"  />
    </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPaperList, battleCollectPaper, batchDownloadPaper, changeCollect } from '@/api/index'
import { wxLogin } from '@/api/login'
import { getSiteInfo, getMemberType } from '@/api/common'
import { onMounted } from 'vue'
import AdBox from '@/components/adBox.vue'
import OnlineBox from '@/components/onlineInfo.vue'
import useUserStore from '@/store/modules/user'

const router = useRouter()
const route = useRoute()

const activeUid = ref('')
const thesisType = ref([])
const hotSearch = ref([])
const navigateList = ref([])
const majorList = ref([])
const cateList = ref([])
const cateUid = ref('')
const searchText = ref('')
const oneIdx = ref(null)
const twoIdx = ref(null)
const twoList = ref([])
const threeIdx = ref(null)
const threeList = ref([])

const toSelectThesisType = (uid, name) => {
    if (uid == 1 || uid == 2) {
        router.push(`/thesisList?categoryUid=${uid}&name=${name}`)
    } else if (uid == 3) {
        router.push(`/jobTitleType?name=${name}&categoryUid=${uid}`)
    } else  {
        router.push(`/moreThesis?name=${name}`)
    }
}
const queryParams = ref({
    startNumbers: null,
    endNumbers: null,
    startDownload: null,
    endDownload: null,
    startUpload: null,
    isTraditionDuplicate: null,
    isAigcDuplicate: null,
    lunwenType: null,
    startDate: null,
    endDate: null,
})
const pageSize = ref(10)
const pageNum = ref(1)
const total = ref(0)
const multipleSelection = ref([])
const tableData = ref([])
const dateRange = ref([])
const searchTypeList = ref([])

watch(() => dateRange.value, (newVal, oldVal) => {
    if (newVal) {
        queryParams.value.startDate = newVal[0]
        queryParams.value.endDate = newVal[1]
    } else {
        queryParams.value.startDate = ''
        queryParams.value.endDate = ''
    }
})

const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
const handleSizeChange = (val) => {
    pageSize.value = val
    getPaperListData()
}
const handleCurrentChange = (val) => {
    pageNum.value = val
    getPaperListData()
}

const toSelectHotSearch = (item) => {
    searchText.value = item
    resetQuery()
}

const resetQuery = () => {
    pageNum.value = 1
    getPaperListData()
}

const toSelectCate = (index) => {
    if (oneIdx.value !== index) {
        oneIdx.value = index
        twoList.value = cateList.value[index].children
        twoIdx.value = null
        threeIdx.value = null
        threeList.value = []
    }
    resetQuery()
}

const toSelectCateTwo = (index) => {
    if (twoIdx.value !== index) {
        twoIdx.value = index
        threeList.value = twoList.value[index].children
        threeIdx.value = null
    }
    resetQuery()
}

const toSelectCateThree = (index) => {
    if (threeIdx.value !== index) {
        threeIdx.value = index
    }
    resetQuery()
}

const getHomeInfo = async () => {
    const res = await getSiteInfo()
    if (res) {
        let { data } = res
        thesisType.value = data?.categoryList
        hotSearch.value = data.hotSearch
        navigateList.value = data.navigateList
        majorList.value = data.majorList
		twoList.value = data.showMajorList
        activeUid.value = data?.categoryList[0]?.groupUid
		if(twoList.value){
			let list = []
			twoList.value.forEach(item => {		   
			    if (item.groupUid === activeUid.value) {
			        list.push(item)
			    }
			})
			twoList.value = list
		}		
        setCategoryList()
        getPaperListData()
    }
}

const setCategoryList = () => {
    let list = []
    majorList.value.forEach(item => {
        item.children = []
        let vals = majorList.value.filter(v => v.categoryPuid == item.categoryUid)
        if(vals.length > 0) {
            item.children = vals
        }

        if (item.groupUid === activeUid.value && item.categoryDepth==0) {
            list.push(item)
        }
    })

    cateList.value = list
}

const getPaperListData = async () => {
    let res = await getPaperList({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        categoryUid: activeUid.value,
        majorUidOne: cateList.value[oneIdx.value]?.categoryUid,
        majorUidTwo: twoList.value[twoIdx.value]?.categoryUid,
        majorUidThree: threeList.value[threeIdx.value]?.categoryUid,
        keyWord: searchText.value,
        ...queryParams.value,
        isTraditionDuplicate: queryParams.value.isTraditionDuplicate ? '1' : null,
        isAigcDuplicate: queryParams.value.isAigcDuplicate ? '1' : null,
    })
    if (res) {
        let { data } = res
        tableData.value = data
        total.value = res.total
    }
}

const toCollectPaper = async (item) => {
    let res = await changeCollect({
        objUid: item.productUid,
        objType: 'good',
    })
    if (res) {
        ElMessage.success(item.isCollect == '0' ? '收藏成功' : '取消收藏成功')
        getPaperListData()
    }
}

const toBatchCollect = async () => {
    let ids = multipleSelection.value.map(item => item.productUid)

    let res = await battleCollectPaper(ids)
    if (res) {
        ElMessage.success('批量收藏成功')
        getPaperListData()
    }
}

const toDownloadPaper = (item) => {
    ElMessageBox.confirm('确定下载该论文吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let res = await batchDownloadPaper({ productIds: [item.productUid] })
        if (res) {
            let { data } = res
            toDownload(data, item.productNo)
            ElMessage.success('下载成功')
            useUserStore().getInfo()
            getPaperListData()
        }
    })
}

const delay = 30000; // 每个元素遍历的延迟时间，单位为毫秒

const delayFunction = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function delayedForEach(array, callback, delay) {
  for (let i = 0; i < array.length; i++) {
    if(i > 0) {
        await delayFunction(delay);
    }
    
    callback(array[i], i, array);
  }
}

const toBatchDownload = () => {
    ElMessageBox.confirm('确定批量下载论文吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let ids = multipleSelection.value.map(item => item.productUid)
        let idCodes = multipleSelection.value.map(item => item.productNo)
        let res = await batchDownloadPaper({ productIds: ids })
        if (res) {
            let { data } = res
            
            let urls = []
            if(typeof data === 'string') {
                urls = data.split(',')
            }else {
                urls = data
            }

            delayedForEach(urls, (url, index) => {
                toDownload(url, url.split('/').slice(-1)[0].split('.')[0])
            }, delay);
            
            ElMessage.success('批量下载成功')
            useUserStore().getInfo()
            getPaperListData()

        }
    })
}

const toDownload = (url, name) => {
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.style.display = 'none';
    a.href = url;
    a.download = `${name}_${new Date().getTime()}`;
    a.click();
}

const hanldeDetail = (item) => {
    router.push(`/thesisDownload/${item.productUid}`)
}

const getSearchType = async () => {
    const res = await getMemberType('paper_app_type')
    if (res) {
        searchTypeList.value = res.data
    }
}

onMounted(() => {
    if(route.query.code) {
        wxLogin({ code: route.query.code }).then(res => {
            let   { data } = res
            useUserStore().setTokenValue(data).then(() => {
                useUserStore().getInfo()
            })
        })
        window.history.replaceState(null, null, location.href.split('?')[0])
    }
    getSearchType()
    getHomeInfo()
})
</script>

<style lang="scss" scoped>
.home-bg {
    background-image: url('https://resources.wendudu.com/images/home-bg.png');
    background-size: cover;
    background-repeat: no-repeat;
    height: 520px;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    pointer-events: none;
}

.home-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 32px 0 0 0;
    position: relative;
    z-index: 10;

    .thesis-type {
        display: flex;
        align-items: center;
        margin-bottom: 32px;

        .item-thesis {
            height: 40px;
            padding: 0 16px;
            border-radius: 34px;
            background: rgba(255, 255, 255, 0.18);
            cursor: pointer;
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            font-weight: 400;
            display: flex;
            align-items: center;
            transition: all 0.2s ease;

            .thesis-type-icon {
                width: 16px;
                height: 16px;
                margin-right: 8px;
            }

            &:not(:last-child) {
                margin-right: 16px;
            }
        }

        .item-thesis-active {
            background-color: #fff;
            color: rgba(250, 143, 33, 1);
        }
    }

    .search-area {
        width: 1100px;
        height: auto;
        padding: 10px;
        border-radius: 16px;
        box-shadow: 0px 10px 40px 0px rgba(0, 0, 0, 0.07);
        background: rgba(255, 255, 255, 0.16);

        .search-box {
            display: flex;
            align-items: center;
            width: 100%;
            height: 60px;
            background: #fff;
            padding: 0 8px 0 24px;
            border-radius: 60px;

            .el-dropdown-link {
                color: rgba(5, 11, 32, 1);
                font-size: 16px;
                line-height: 28px;
                display: flex;
                align-items: center;
                justify-content: center;
                width: 108px;
				/*
                &::after {
                    content: '';
                    border: 4px solid rgba(5, 11, 32, 1);
                    margin-left: 16px;
                    transform: rotate(45deg);
                    border-top-color: transparent;
                    border-left-color: transparent;
                    position: relative;
                    top: -2px;
                }*/
            }

            .search-input {
                flex: 1;
                height: 36px;
                padding-left: 8px;
                border-left: 1px solid rgba(233, 233, 233, 1);
                margin-left: 12px;
            }

            .seach-icon {
                width: 56px;
                height: 56px;
                border-radius: 50%;
                background: rgba(51, 133, 255, 1);
                padding: 16px;
                cursor: pointer;
            }
        }

        .hot-search {
            margin-top: 10px;
            display: flex;
            align-items: center;
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            font-weight: 500;
            line-height: 29.6px;

            .hot-search-list {
                margin-left: 16px;
                flex: 1;
                overflow: hidden;

                .item-hot-search {
                    cursor: pointer;

                    &:not(:last-child) {
                        margin-right: 16px;
                    }

                    &:hover {
                        text-align: underline;
                    }
                }
            }
        }
    }

    .filter-data-content {
        padding: 16px 0 40px 0;
        width: 100%;
        min-height: 640px;
        border-radius: 40px 40px 0px 0px;
        background: rgba(248, 248, 248, 1);
        margin-top: 24px;

        .filter-box {
            width: 1100px;
            height: auto;
            margin: 0 auto;
            border-radius: 16px;
            background-color: #fff;
            padding: 12px 24px 8px 12px;
            margin-bottom: 12px;

            .item-filter-type {
                display: flex;

                &:not(:last-child) {
                    border-bottom: 1px solid rgba(233, 233, 233, 1);
                    margin-bottom: 12px;
                }

                .item-filter-label {
                    color: rgba(5, 11, 32, 1);
                    font-size: 14px;
                    font-weight: 700;
                    line-height: 30px;
                    margin-right: 24px;
                }

                .item-filter-list {
                    flex: 1;
                    display: flex;
                    flex-wrap: wrap;

                    .item-filter {
                        color: rgba(145, 153, 163, 1);
                        font-size: 14px;
                        font-weight: 500;
                        line-height: 30px;
                        padding-bottom: 6px;
                        cursor: pointer;

                        &:not(:last-child) {
                            margin-right: 24px;
                        }
                    }

                    .item-filter-active {
                        color: rgba(51, 133, 255, 1);
                        font-weight: 700;
                    }
                }
            }
        }

        .data-table {
            width: 1100px;
            height: auto;
            margin: 0 auto;
            border-radius: 16px;
            background: rgba(255, 255, 255, 1);
            padding: 2px 0 24px;
            position: relative;

            .product-name {
                color: rgba(51, 133, 255, 1);
                cursor: pointer;
            }

            .item-score {
                display: flex;
                align-items: center;
                justify-content: center;
                color: rgba(102, 102, 102, 1);
                font-size: 14px;
                font-weight: 500;
                line-height: 30px;

                .item-score-icon {
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                }
            }

            .item-status-icon {
                display: flex;
                align-items: center;
                justify-content: center;

                img {
                    width: 16px;
                    height: 16px;
                }
            }

            .opt-btn {
                display: flex;
                align-items: center;

                .item-opt-img {
                    width: 16px;
                    height: 16px;
                    cursor: pointer;

                    &:not(:last-child) {
                        margin-right: 24px;
                    }
                }
            }

            .pagination-batch {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: 24px;
                padding: 0 24px;
            }
        }
    }

    .search-section {
        width: 1100px;
        height: auto;
        margin: 0 auto;
        border-radius: 16px;
        background-color: #fff;
        padding: 12px 24px 8px 12px;
        margin-bottom: 16px;

        .form-flex {
            display: flex;
            align-items: center;
        }
        .form-end {
            display: flex;
            justify-content: flex-end;
        }
        .form-spaceBetween {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
    }

    .search-input {
        ::v-deep {
            .el-input__wrapper {
                box-shadow: none;
            }
        }
    }

    ::v-deep {
        .el-table th.el-table__cell {
            background: rgba(244, 247, 255, 1);
            border-bottom-color: transparent;
            color: rgba(5, 11, 32, 1);
        }
        label {
            font-weight: 400;
        }
    }
}
</style>